<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <Tree :name="this.name" @projectSelect="isDevice" @deviceSelect="isDevice" style="margin-left: 20px;"></Tree>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="设备编码" prop="deviceId">
            <el-input v-model="queryParams.deviceId" placeholder="请输入设备编码" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="所属项目" prop="deptName">
            <el-input v-model="queryParams.deptName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:device:add']">新增设备</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:device:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:device:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['system:device:export']">导出</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button size="mini" type="success" icon="el-icon-time" @click="timing">校时</el-button>

          </el-col>
          <el-col :span="1.5">
            <el-button size="mini" type="success" icon="el-icon-cloudy" @click="parameter">远端参数</el-button>

          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 设备参数/ -->
        <el-dialog title="设备参数" :visible.sync="dialogTableVisible" width="800px">
          <ParaMeter :ID="timeDeviceID" @closed="closed"></ParaMeter>
        </el-dialog>
        <!-- 设备参数/ -->
        <el-table v-loading="loading" ref="table" :data="deviceList" @selection-change="handleSelectionChange"
          @select="handleSelect">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="设备编码" align="center" prop="deviceId" />
          <el-table-column label="所属项目" align="center" prop="deptName" />
          <el-table-column label="设备名称" align="center" prop="deviceName" />
          <el-table-column label="设备状态" align="center" prop="statusLable">
            <template slot-scope="scope">
              <el-tag :type="scope.row.statusLable == '离线' ? 'danger' : 'success'"> {{ scope.row.statusLable }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createUserId" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:device:edit']">修改</el-button>
              <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleFactors(scope.row)">环境因子</el-button> -->
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:device:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改device对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备编码" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备编码" :disabled="Xshow" required :maxlength="8" />
        </el-form-item>
        <el-form-item label="所属项目" prop="deptId">
          <treeselect v-model="form.deptId" :options="projectList" :normalizer="normalizer" placeholder="选择所属项目"
            @select="ProjectChange" />
        </el-form-item>
        <el-form-item label=" 设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
          <el-button type="text" v-click="Mapclick">地图选点</el-button>
        </el-form-item>
        <el-form-item label="离线时间" prop="offlineTime">
          <el-input v-model="form.offlineTime" placeholder="请输入离线时间" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="isLoading" @click="submitForm">
          <span v-if="isLoading"><i class="el-icon-loading"></i> {{ text }}</span>
          <span v-else>确 定</span>
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="Mapshow">

      <Map style="z-index: 999;"></Map>

    </el-dialog>
    <el-dialog :title="title" :visible.sync="factorOpen" width="1000px" append-to-body>
      <el-table v-loading="loading" :data="factorList" @selection-change="handleSelectionChange">
        <el-table-column label="因子名称" align="center" prop="factorName" />
        <el-table-column label="上限" align="center" prop="ceiling" />
        <el-table-column label="下限" align="center" prop="floor" />
        <el-table-column label="报警状态" align="center" prop="warnType">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.warnType" active-value="0" inactive-value="1"
              @change="changeWarnType(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateFactor(scope.row)"
              v-hasPermi="['system:factor:edit']">修改因子</el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:factor:remove']">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 环境因子修改 -->
      <!-- 添加或修改SysEnvironmentalFactor对话框 -->
      <el-dialog :title="title" :visible.sync="innerOpen" width="500px" append-to-body>
        <el-form ref="factorForm" :model="factorForm" :rules="rules" label-width="80px">
          <el-form-item label="因子名称" prop="factorName">
            {{ factorForm.factorName }}
          </el-form-item>
          <el-form-item label="告警上限" prop="ceiling">
            <el-input v-model="factorForm.ceiling" placeholder="请输入告警上限" />
          </el-form-item>
          <el-form-item label="告警下限" prop="floor">
            <el-input v-model="factorForm.floor" placeholder="请输入告警下限" />
          </el-form-item>
          <el-form-item label="是否告警" prop="floor">
            <el-switch v-model="factorForm.warnType" active-value="0" inactive-value="1" />
            <!-- <el-switch v-model="factorForm.warnType" @change="changeWarnType" active-value="1"
              inactive-value="0"/> -->
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFactorForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

    </el-dialog>

  </div>
</template>

<script>
import Tree from "@/components/Tree/Tree";
import ParaMeter from "./parameter.vue"
import EventBus from "../../../utils/map/click";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listDevice, NewdeptTreeSelect, getDevice, delDevice, addDevice, updateDevice, deptTreeSelect, calibrationtime, listDept } from "@/api/system/device";
import { getFactor, listFactor, updateFactor } from "@/api/system/factor"
import Map from './map.vue'
import { color } from 'echarts';
export default {
  name: "Device",
  directives: {
    click: {
      bind(el, binding) {
        el.addEventListener('click', binding.value);
      },
      unbind(el, binding) {
        el.removeEventListener('click', binding.value);
      }
    }
  },
  components: {
    Map,
    ParaMeter,
    Treeselect,
    Tree
  },
  data() {

    return {
      name: '',
      placeholderText: "",
      text: "",
      projectList: [],
      isLoading: false,
      Mapshow: false,
      Xshow: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // device表格数据
      deviceList: [],
      factorList: [],
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      props: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      // 弹出层标题
      title: "",
      //修改因子弹出标题
      factor: "",
      // 是否显示弹出层
      open: false,
      factorOpen: false,
      innerOpen: false,
      // 查询参数
      queryParams: {
        status: "3",
        deviceId: "",
        pageNum: 1,
        pageSize: 10,
        deptName: null,
      },
      query: {
        deviceId: ""
      },
      // 表单参数
      form: {
        deviceId: "",
        deptId: '',
        ancestors: '',
        deptName: '',
        longitude: '',
        latitude: "",
        offlineTime: '',
      },
      factorForm: {},
      // 表单校验
      rules: {
        deviceId: [
          { pattern: /^\d{8}$/, message: '设备编码必须为8位数字', trigger: 'blur', required: true }
          // 可以添加其他验证规则
        ],
        deptName: [
          { required: true, message: '请选择项目', trigger: 'blur' }
        ],
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ]
        ,
        longitude: [
          { required: true, message: '请输入经度', trigger: 'blur' }
        ]
        ,
        latitude: [
          { required: true, message: '请输入纬度', trigger: 'blur' }
        ],
        offlineTime: [
          { required: true, message: '请输入离线时间,默认为5分钟', trigger: 'blur' }
        ]
      },
      timeDeviceID: null,//校准设备ID
      timeDeviceList: [],//校准设备数组
      dialogTableVisible: false,
      //Tree加载样式
      loadingNodeId: null,
      Namelist: []
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.name = this.$route.name
    this.getList();
    this.getDeptTree();
    EventBus.$on('JWD', (data) => {
      this.form.longitude = data.J
      this.form.latitude = data.W
    })
  },
  mounted() {
    // this.Projectselect()
  },
  methods: {
    isDevice(e) {
      if (e.devId) {
        this.queryParams.deviceId = e.id
        this.queryParams.deptId = ''
      }
      else {
        this.queryParams.deviceId = ''
        this.queryParams.deptId = e.id
      }
      console.log(this.queryParams);
      this.handleQuery()
    },
    // 懒加载树加载数据
    loadNode(node, resolve) {
      if (node.level > 0) {
        if (!node.data.children) {
          this.$set(node.data, 'children', []);
          // this.queryParams.deptId = node.data.id;
          // this.getList();
          // const newNode = this.deviceList.map(item => ({
          //   id: item.deviceId,
          //   label: item.deviceName
          // }))
          // node.data.children.push(...newNode)

          listDevice({ status: 3, deptId: node.data.id }).then(res => {
            const newNode = res.rows.map(item => ({
              id: item.deviceId,
              label: item.deviceName
            }))
            node.data.children.push(...newNode)
          })
        }
        return resolve(node.data.children);
      }
      setTimeout(() => {
        const data = this.deptOptions
        resolve(data);
      }, 500);
    },
    //Tree加载样式
    renderContent(h, { node, data }) {
      let label = h('span', node.label);
      // 如果当前节点正在加载数据，则显示加载图标
      if (this.loadingNodeId === data.id) {
        let loadingIcon = h('i', { class: 'el-icon-loading' });
        return h('span', [loadingIcon, label]);
      }
      // 否则只显示标签
      return label;
    },
    closed() {

    },
    /** 转换项目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    parameter() {
      if (Object.keys(this.timeDeviceList).length === 0) {
        this.$message({
          showClose: true,
          message: '请先选择一台设备!',
          type: 'danger'
        });
      } else if (this.timeDeviceList.status == '在线' || this.timeDeviceList.statusLable == '在线') {
        this.timeDeviceID = this.timeDeviceList.deviceId
        this.dialogTableVisible = true
        console.log(this.timeDeviceID)
      } else {
        this.$message({
          showClose: true,
          message: '离线设备不能操作',
          type: 'erroe'
        });
      }
    },
    //校准时间
    timing() {
      if (Object.keys(this.timeDeviceList).length === 0) {
        this.$message({
          showClose: true,
          message: '请先选择一台设备!',
          type: 'danger'
        });
      } else if (this.timeDeviceList.status == '在线' || this.timeDeviceList.statusLable == '在线') {
        calibrationtime({ deviceId: this.timeDeviceList.deviceId }).then(res => {
          if (res) {
            this.$message({
              showClose: true,
              message: '校时成功!',
              type: 'success'
            });
          } else {
            this.$message({
              showClose: true,
              message: '校时失败!',
              type: 'erroe'
            });
          }
        })



      } else {
        this.$message({
          showClose: true,
          message: '校时失败!',
          type: 'error'
        });
      }


    },
    //表格选中事件
    handleSelect(select, row) {
      console.log("123")
      console.log(select, row)
      this.$refs.table.clearSelection();
      // 设置当前点击的行为选中状态  只能单选
      this.$refs.table.toggleRowSelection(row);
      this.timeDeviceList = select[select.length - 1]
      console.log(this.timeDeviceList)
    },
    transformNode(node) {
      const { id, label, children } = node;
      const newNode = { value: id, label };
      return newNode;
    },
    ProjectChange(node, instanceId) {
      console.log(node);
      // node.ancestors = node.ancestors.join(node.deptId)

      this.form.ancestors = node.ancestors + ',' + node.deptId;
      console.log(this.form);

    },
    Mapclick() {
      this.Mapshow = !this.Mapshow;
    },
    /** 查询device列表 */
    async getList() {
      this.loading = true;
      await listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询环境因子列表 */
    getFactor(id) {
      listFactor(id).then(response => {
        this.factorList = response.rows;
        this.factorOpen = true;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      NewdeptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    treeNodeClick(data, node) {
      console.log(data);
      this.queryParams.deptId = ''
      this.queryParams.deviceId = ''
      // 根据当前节点层级判断
      if (node.level > 1) {
        if (data.children.length > 0) {
          this.queryParams.deptId = node.data.id
          this.queryParams.deviceId = ''
        } else {
          this.queryParams.deptId = ''
          this.queryParams.deviceId = node.data.id
        }
      }
      this.handleQuery();
    },
    // 节点单击事件
    async handleNodeClick(data) {
      // //只能单选时间
      // const { checked, indeterminate } = this.$refs.tree.getNode(data.id);
      // if (checked) {
      //   //如果是true说明点击其他节点时有其他复选框是勾选状态取消勾选不能发送请求
      //   console.log("取消选中")
      //   this.$refs.tree.setChecked(data.id, false);
      // } else {
      //   // 先将所有节点设置为非选中状态，再将当前节点设置为选中状态发送请求
      //   this.$refs.tree.setCheckedNodes([]);
      //   this.$refs.tree.setChecked(data.id, true);
      //   //在这里清空参数是因为如果我只想点击节点去查看数据的话，如果此时搜索框里有时间就会带着数据区查询，会找不到结果，所以点击节点的时候要先清空搜索框里的数据
      this.loadingNodeId = data.id;
      try {
        const DAta = await listDevice({ status: 3, deptId: data.id })
        this.loadingNodeId = null;

        if (!data.children) {
          this.$set(data, 'children', [])
        }
        if (DAta.rows.length > 0) {
          const newNode = DAta.rows.map(item => ({
            id: item.deviceId,
            label: item.deviceName
          }))
          data.children.push(...newNode)
          this.$refs.tree.updateKeyChildren(data.id, data.children)
        }
        this.reset()

        if (data.children.length > 0) {
          //在这里通过判断是否有children来判断是项目还是设备
          this.queryParams.deviceId = ''
          this.queryParams.deptId = data.id
        } else {
          this.queryParams.deptId = ''
          this.queryParams.deviceId = data.id
        }
        console.log(this.queryParams)

        this.handleQuery();

      } catch (err) {
        this.loadingNodeId = null;
      }

    },
    isObject(obj) {
      return obj !== null && typeof obj === 'object'
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.innerOpen = false
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        deptName: null,
        deptId: null,
        deviceName: null,
        longitude: null,
        latitude: null,
        offlineTime: null,
        createTime: null,
        createUserId: null,
        ancestors: null,
      };
      this.factorForm = {
        id: null,
        deviceId: null,
        factorName: null,
        factorType: null,
        ceiling: null,
        floor: null,
        warnType: null
      }
      this.resetForm("form", "factorForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.reset()
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.queryParams.deviceId = undefined
      this.$refs.tree.setCurrentKey(null);
      this.$refs.tree.setCheckedNodes([]);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.offlineTime = 5
      this.placeholder = ''
      this.open = true;
      this.title = "添加设备";
      this.Xshow = false,
        this.text = "正在添加..."
      // deptName
      listDept().then(response => {
        this.Namelist = response.data
        this.projectList = this.handleTree(response.data, "deptId");
      });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      listDept().then(response => {
        this.Namelist = response.data
        this.projectList = this.handleTree(response.data, "deptId");
      });

      this.reset();
      listDept().then(response => {
        this.Namelist = response.data
        this.projectList = this.handleTree(response.data, "deptId");
      });
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.placeholderText = response.data.deptName
        this.open = true;
        this.title = "修改设备";
        this.text = "正在修改..."
      });
      this.Xshow = true
    },
    findDepartment(data, deptId) {
      for (let item of data) {
        if (item.value == deptId) {
          return item.label;
        } else if (item.children) {
          const result = this.findDepartment(item.children, deptId);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    /**环境因子列表 */
    handleFactors(row) {
      this.reset();
      this.query.deviceId = row.deviceId;
      listFactor(this.query).then(response => {
        this.factorList = response.rows;
        this.factorOpen = true;
        this.title = "环境因子";
      });
    },
    /**修改环境因子 */
    handleUpdateFactor(row) {
      this.reset();
      const id = row.id || this.ids
      getFactor(id).then(response => {
        this.factorForm = response.data;
        this.innerOpen = true;
        this.title = "修改环境因子项";
      });
    },
    changeWarnType(e) {
      this.query.deviceId = e.deviceId;
      updateFactor(e).then(response => {
        this.$modal.msgSuccess("修改成功");
        listFactor(this.query).then(response => {
          this.factorList = [];
          this.factorList = response.rows;
        });
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.isLoading = true; // 禁用按钮，显示加载状态
      this.Namelist.forEach(item => {
        if (item.deptId == this.form.deptId) {
          this.form.deptName = item.deptName
        }
      })
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.isLoading = false; // 启用按钮，隐藏加载状态
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.isLoading = false; // 启用按钮，隐藏加载状态
            });
          }
        } else {
          this.isLoading = false; // 启用按钮，隐藏加载状态
        }
      });
    },
    /** 提交环境因子修改按钮 */
    submitFactorForm() {
      this.$refs["factorForm"].validate(valid => {
        if (valid) {
          updateFactor(this.factorForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.innerOpen = false;
            listFactor(this.query).then(response => {
              this.factorList = [];
              this.factorList = response.rows;
            });
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除device编号为"' + ids + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
